﻿namespace Basic.Repository.SqlSugar;

public class BaseDBConfig
{
    public static DBConfig DBConfObj { get; set; }

    public static (List<MultiDBOperate> allDbs, List<MultiDBOperate> slaveDbs) MultiConnectionConf => MutiInitConn();

    public static (List<MultiDBOperate>, List<MultiDBOperate>) MutiInitConn()
    {
        List<MultiDBOperate> listdatabase = DBConfObj.DataBase.Where(i => i.Enabled).ToList();
        List<MultiDBOperate> listdatabaseSimpleDB = new List<MultiDBOperate>();//单库
        List<MultiDBOperate> listdatabaseSlaveDB = new List<MultiDBOperate>();//从库

        // 单库，且不开启读写分离，只保留一个
        if (!DBConfObj.CQRSEnabled && !DBConfObj.MutiDBEnabled)
        {
            if (listdatabase.Count == 1)
            {
                return (listdatabase, listdatabaseSlaveDB);
            }
            else
            {
                var dbFirst = listdatabase.FirstOrDefault(d => d.ConnId == DBConfObj.MainDb) ?? listdatabase.FirstOrDefault();
                listdatabaseSimpleDB.Add(dbFirst);
                var others = listdatabase.Where(s => s.ConnId != DBConfObj.MainDb).ToList();
                listdatabaseSimpleDB.AddRange(others);
                return (listdatabaseSimpleDB, listdatabaseSlaveDB);
            }
        }
        // 读写分离，且必须是单库模式，获取从库
        if (DBConfObj.CQRSEnabled && !DBConfObj.MutiDBEnabled)
        {
            if (listdatabase.Count > 1)
            {
                listdatabaseSlaveDB = listdatabase.Where(d => d.ConnId != DBConfObj.MainDb.ToString()).ToList();
            }
        }
        return (listdatabase, listdatabaseSlaveDB);
    }

}